package com.shenyi.mould.rest.controller.base;

import com.shenyi.core.utils.oss.OssClient;
import com.shenyi.wx.annotation.IgnoreAuth;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yikun.he
 * @version 1.0
 * @date 2019/2/11
 * @desc
 * @see
 * @since 1.0
 */
@RestController
@RequestMapping("/api/oss")
public class OssController {

    /**
     * 获取参数
     *
     * @return
     */
    @GetMapping("/param")
    public Map<String, String> param() {
        return OssClient.getParam();
    }

    /**
     * 获取上传路径
     *
     * @param key
     * @return
     */
    @GetMapping("/url")
    public String url(@RequestParam(name = "key") String key) {
        return OssClient.getUrl(key);
    }

    /**
     * 上传文件
     */
    @PostMapping("/file-upload")
    @IgnoreAuth
    public Map<String, Object> fileUpload(@RequestParam("file") MultipartFile multipartFile) {
        if (multipartFile.isEmpty()) {
            return new HashMap<>();
        }
        String fileName = multipartFile.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        // 文件的名称
        try {
            InputStream inputStream = multipartFile.getInputStream();
            String url = OssClient.upload(inputStream, suffix);
            return new HashMap<String, Object>(1) {{
                put("url", url);
            }};
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new HashMap<>();
    }
}
